from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection

from users.models import User
from .models import OAuthQQUser
from .utils import check_save_user_token


class OauthUserSerializer(serializers.Serializer):
    """注册序列化器"""
    # 定义序列化和反序列化的字段
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(label='短信验证码')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)

    class Meta:
        model = OAuthQQUser
        # 模型中没有的字段(不需要保存): password, allow, sms_code
        fields = ['user', 'mobile', 'password', 'sms_code', 'openid']

    # 校验
    def validate(self, data):
        # 获取openid
        openid_token = data.get('access_token')  # 获取加密的openid
        openid = check_save_user_token(openid_token)  # 把加密的openid还原
        if not openid:
            raise serializers.ValidationError('openid无效')
        # 把解密后的openid存到反序列化的字典中,后续保存的使用
        data['openid'] = openid

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_code')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if not real_sms_code:
            raise serializers.ValidationError('无效的短信验证码')
        if real_sms_code.decode() != data['sms_code']:
            raise serializers.ValidationError('短信验证码有误')

        # 校验密码
        try:
            user = User.objects.get(mobile=data['mobile'])
        except User.DoseNotExist:
            # 如果用户不存在,直接返回
            pass
        else:
            # 如果用户存在,校验密码
            if not user.check_password(data['password']):
                raise serializers.ValidationError('密码错误')
            # 将user加到反序列化的字典中,以备以后使用
            data['user'] = user
        return data

    # 重写create方法
    def create(self, validated_data):
        openid = validated_data['openid']
        user = validated_data['user']
        # 用户不存在,创建user
        if not user:
            user = User.objects.create(
                username=validated_data['mobile'],
                mobile=validated_data['mobile'],
                password=validated_data['password'],
            )
        # 将user和openid绑定
        oauth_user = OAuthQQUser(openid=openid, user_id=user.id)
        oauth_user.save()

        return user



